<template>
	<view class="login-container">
		<uni-icons type="contact-filled" size="100" color="#AFAFAF"></uni-icons>
		<!-- <button type="primary" class="btn-login" open-type="getUserInfo" @getuserinfo="getUserInfo">一键登录</button> -->
		<button type="primary" class="btn-login" @click="getUserPro">一键登录</button>
		<text class="tips-text">登录后尽享更多权益</text>
	</view>
</template>

<script>
	import {mapMutations, mapState} from 'vuex';
	
	export default {
		name:"my-login",
		data() {
			return {
				
			};
		},
		computed: {
			...mapState('m_user', ['redirectInfo']),
		},
		methods: {
			...mapMutations('m_user', ['updateUserInfo', 'updateToken', 'updateRedirectInfo']),
			//点击一键登录
			getUserInfo(e){
				console.log(e);
				
				if(e.detail.errMsg === 'getUserInfo:fail auth deny'){
					//用户取消了授权
					return uni.$showMsg('您取消了登录授权！');
				}
				
				console.log('e.detail.userInfo:');
				console.log(e.detail.userInfo);
			},
			//获取用户信息
			getUserPro(){
				uni.getUserProfile({
					desc: '用户信息仅用于登录',
					success: (e) => {
						this.updateUserInfo(e.userInfo);
						this.getToken(e);
					},
					fail: (e) => {
						if(e.errMsg === 'getUserProfile:fail auth deny'){
							//用户取消了授权
							return uni.$showMsg('您取消了登录授权！');
						}
					},
				})
			},
			//登录
			async getToken(info){
				const [err, res] = await uni.login().catch(err => err);
				
				if(err || res.errMsg !== 'login:ok'){
					//登录失败
					return uni.$showMsg('登录失败！');
				}
				
				const query = {
					code: res.code,
					encryptedData: info.encryptedData,
					iv: info.iv,
					rawData: info.rawData,
					signature: info.signature,
				}
				
				const {data: resLogin} = await uni.$http.post('/api/public/v1/users/wxlogin', query);
				
				if(resLogin.meta.status === 200){
					//请求失败
					return uni.$showMsg('登录失败！');
				}
				
				resLogin.message = {
					token: 'sdjfldjfdsgosudgosdlgshdogsudoguseogeugerferrgg',
				}
				
				this.updateToken(resLogin.message.token);
				this.navigateBack();
			},
			//跳转回之前的页面
			navigateBack(){
				if(this.redirectInfo && this.redirectInfo.openType === 'switchTab'){
					//有登录后跳转至页面的信息，是 tabBar 跳转
					uni.switchTab({
						url: this.redirectInfo.from,
						complete: () => {
							this.updateRedirectInfo(null);
						},
					});
				}
			},
		},
	}
</script>

<style lang="scss">
page {
	background-color: white;
	.login-container {
		height: 750rpx;
		background-color: #F8F8F8;
		display: flex;
		flex-direction: column;
		justify-content: center;
		align-items: center;
		position: relative;
		overflow: hidden;
		&::after {
			content: ' ';
			display: block;
			width: 100%;
			height: 40px;
			border-radius: 100%;
			position: absolute;
			left: 0;
			bottom: 0;
			transform: translateY(50%);
			background-color: white;
			// background-color: #F8F8F8;
		}
		.btn-login {
			background-color: #C00000;
			border-radius: 100px;
			width: 90%;
			margin: 15px 0;
		}
		.tips-text {
			color: gray;
			font-size: 12px;
		}
	}
}
</style>
